import numpy as np

class DynamicTrustCalculator:
    def __init__(self, decay_rate=0.05):
        self.decay_rate = decay_rate
        self.historical_trust = {}

    def direct_trust(self, g_i: np.ndarray, g_j: np.ndarray) -> float:
        """
        Calculate direct trust using gradient similarity (Eq.3)
        Args:
            g_i: Gradient vector of node i
            g_j: Gradient vector of node j
        Returns:
            TD_ij: Direct trust value in [0,1]
        """
        cos_sim = np.dot(g_i, g_j) / (np.linalg.norm(g_i) * np.linalg.norm(g_j))
        return max(0, cos_sim)  # ReLU activation
    
    def behavioral_consistency(self, y_actual: float, y_predicted: float, delta=0.1) -> float:
        """
        Quantify behavioral stability (Eq.4)
        Args:
            y_actual: Observed behavior at t+1
            y_predicted: Predicted behavior at t+1
        Returns:
            Stability metric in [0,1]
        """
        return 1 - abs((y_actual - y_predicted) / max(y_actual, delta))
    
    def global_reputation(self, node_id: int, current_trust: float, timestamp: float) -> float:
        """
        Calculate time-decayed global reputation (Eq.7)
        Args:
            node_id: Client identifier
            current_trust: Current consensus trust value
            timestamp: Current time index
        Returns:
            Updated global reputation
        """
        prev_reputation = self.historical_trust.get(node_id, 0)
        gamma = np.exp(-self.decay_rate * timestamp)  # Forgetting factor
        return gamma * prev_reputation + (1 - gamma) * current_trust
